package com.ec50n9.server.auth

import cn.dev33.satoken.stp.SaTokenInfo
import cn.dev33.satoken.stp.StpUtil
import com.ec50n9.server.module.common.renderTo
import com.ec50n9.server.module.user.UserCreateForm
import com.ec50n9.server.module.user.UserQueryRendered
import com.ec50n9.server.module.user.UserService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import javax.validation.constraints.NotBlank

@Tag(name = "认证管理")
@RestController
@RequestMapping("/api/auth")
class AuthController(private val userService: UserService) {

    @Operation(summary = "注册用户")
    @PostMapping("/register")
    fun register(@RequestBody @Validated createForm: UserCreateForm): UserQueryRendered =
        userService
            .newOne(createForm.renderTo())
            .renderTo(UserQueryRendered::class.java)

    @Operation(summary = "登录并获取token")
    @PostMapping("/token")
    fun login(@RequestBody @Validated loginForm: AuthLoginForm): SaTokenInfo {
        val user = userService.authenticateUser(loginForm.username!!, loginForm.password!!)
        StpUtil.login(user.username)
        return StpUtil.getTokenInfo()
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/self")
    fun getSelf() =
        userService.findOneByUsername(StpUtil.getLoginIdAsString()).renderTo(UserQueryRendered::class.java)

    @Operation(summary = "登出")
    @DeleteMapping("/logout")
    fun logout() {
        StpUtil.logout()
    }
}

data class AuthLoginForm(
    @field:NotBlank(message = "用户名不能为空")
    var username: String? = null,
    @field:NotBlank(message = "密码不能为空")
    var password: String? = null
)